package com.wang.springbootinit.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.wang.springbootinit.model.result.ExcelHandleInfoResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Data
public class ExcelNoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    //传过来图表的id
    private Long chartId;

    private Boolean isSyncChart;

    public ExcelNoModelDataListener(Long chartId, Boolean isSyncChart) {
        this.chartId = chartId;
        this.isSyncChart = isSyncChart;
    }

//    @Resource
//    private AmqpTemplate amqpTemplate;

    //处理excel的交换机和topic
    final String excelExchange = "ExcelTopicExchange";
    final String excelTopic = "topic.excel.saveData";

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     * 一次mq消息最多发送五万条数据，超过则要再次发送mq消息再次保存，可能会导致数据更新不及时的问题
     */
    private static final int BATCH_COUNT = 100000;
    //数据行信息
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private List<String> excelHeadList = new ArrayList<>();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        for (int i = 0; i < headMap.size(); i++) {
            excelHeadList.add(i,headMap.get(i));
        }
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("excel所有数据解析完成");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，发送mq消息！", cachedDataList.size());
        ExcelHandleInfoResult excelHandleInfoResult = new ExcelHandleInfoResult(this.chartId, this.isSyncChart, this.excelHeadList,this.cachedDataList);
        //发送mq消息，保存excel数据
//       todo  amqpTemplate.convertAndSend(excelExchange, excelTopic, excelHandleInfoResult);
    }
}
